import { Injectable } from '@angular/core'
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'
import { Observable, of, Subject } from 'rxjs'
import { NzModalService } from 'ng-zorro-antd'

import { AcquirerNewComponent } from 'app/routes/acquirer/new/new.component'
import { PageService } from '@shared/services/page.service'
import { I18NService } from '@core'

@Injectable()
export class NewRouterGuardClass implements CanDeactivate<AcquirerNewComponent> {
  constructor(
    private modal: NzModalService,
    private pageService: PageService,
    private i18n: I18NService,
  ) {}

  canDeactivate(
    component: AcquirerNewComponent,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot,
  ): Observable<boolean> {
    const result = new Subject<boolean>()
    const isAlive = this.pageService.isGuardAlive
    if (!isAlive ) {
      this.pageService.triggerGuardAlive(true) // 将守卫恢复
      return of(true)
    } else {
      this.showConfirmModal(result)
      return result
    }
  }

  showConfirmModal(result: Subject<boolean>): void {
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.CANCEL_DATA_CREATING_CONFIRM'),
      nzOnOk: () => {
        /* TODO 需要将 store service 中的数据 reset */
        result.next(true)
      },
      nzOnCancel: () => result.next(false),
    })
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
